package com.example.qr;

import java.io.FileNotFoundException;

import android.graphics.Bitmap;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

/**
 * This class contains static functions that specialize in decoding a QR code from an image.
 * @author Administrator
 *
 */

public final class QRDecoder {

	/**
	 * This class is not supposed to be instantiated for public use.
	 */
	private QRDecoder() {
		
	}
	
	/**
	 * TODO Reconsider the return value of this function.
	 * Given an image containing QRCode under absolute file path format, return the decoded message.
	 * @param absFilePath
	 * @return The decoded message, or an error message
	 */
	
	public static String decodeImage(String absFilePath) {
		try {
			Bitmap bmp = CustomBitmapFactory.bitmapFromFile(absFilePath);
			return decodeImage(bmp);
		} catch (FileNotFoundException e) {
			
		}
		return "Temporary image file not found.";
	}
	
	/**
	 * TODO Reconsider the return value of this function.
	 * Given a bitmap image possibly containing QR code, return the decoded message.
	 * @param absFilePath
	 * @return The decoded message, or an error message
	 */
	
	public static String decodeImage(Bitmap bitmap) {
		String error = "";
		QRCodeReader reader = new QRCodeReader();
		try {
			RGBLuminanceSource src = new RGBLuminanceSource(bitmap);
			HybridBinarizer binary = new HybridBinarizer(src);
			BinaryBitmap bmp = new BinaryBitmap(binary);
			Result res = reader.decode(bmp);
			reader.reset();
			return res.getText();
		} 
		catch (OutOfMemoryError e) {
			reader.reset();
			error = "Not enough memory to decode this image.";
		}
		catch (NotFoundException e) {
			error = "NotFoundException (No legible data)";
		} 
		catch (ChecksumException e) {
			error = "ChecksumException";
		} 
		catch (FormatException e) {
			error ="FormatException";
		} 
		catch (Exception e) {
			error = "No legible data was gleaned.";
		}    	
		return error;
	}
	
	
}
